<template>
  <div class="zygl-Upload">
    <el-card>
      <div class="content">
        <el-row class="title">
          <div class="crumbs">
            <el-breadcrumb separator=">">
              <el-breadcrumb-item :to="{ path: '/teacher/zygl' }">资源管理</el-breadcrumb-item>
              <el-breadcrumb-item>上传资源</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="upload-button">
            <el-button type="success"
                       @click="handleUpload">确认上传</el-button>
            <el-button type="success"
                       @click="goback">返回</el-button>
          </div>
        </el-row>
        <el-row class="main">
          <el-col :span="7"
                  class="left">
            <div class="cover">
              <img v-if="previewCover"
                   :src="previewCover"
                   class="cover"
                   alt="头像"
                   width="178px"
                   height="178px">
              <i v-else
                 @click="handleUploadCover"
                 class="el-icon-plus cover-uploader-icon"></i>
            </div>
            <el-button type="success"
                       style="margin-top:20px;"
                       @click="handleUploadCover">上传封面</el-button>
            <input type="file"
                   name="file"
                   ref="cover"
                   style="display:none;"
                   @change="uploadCover">
          </el-col>
          <el-col :span="9"
                  class="right">
            <el-form :model="resourceForm">
              <el-form-item label="上传资源">
                <el-button type="success"
                           class="uploadImg"
                           style="margin:-2px;padding:7px 15px;"
                           @click="handleUploadResource">选择</el-button>
                <span style="margin-left:20px;font-size:16px">{{resourceForm.name}}</span>
                <input type="file"
                       @change="uploadResource"
                       ref="resource"
                       style="display:none;">
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-dialog title="上传进度"
               :visible.sync="uploadDialogVisible"
               width="40%"
               top="30vh"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false">
      <el-progress :text-inside="true"
                   :stroke-width="18"
                   :percentage="uploadProgress"
                   status="success"></el-progress>
    </el-dialog>
  </div>
</template>

<script>
import { parseDataToTree } from 'utils'
export default {
  data() {
    return {
      input: '',
      knowledgeCate: [],
      props: {
        label: 'name',
        children: 'children'
      },
      resourceForm: {
        knowCateIds: '',
        title: '',
        resourceType: '',
        brief: '',
        md5value: '',
        iconMd5value: '',
        name: '',
        guid: ''
      },
      previewCover: '',
      previewResource: '',
      uploadProgress: 0,
      uploadDialogVisible: false
    }
  },
  created() {
    this.getAllKnowledgeCate()
  },
  methods: {
    getAllKnowledgeCate() {
      this.$api.getAllKnowledgeCate().then(response => {
        this.knowledgeCate = parseDataToTree(response)
      })
    },
    // 打开上传封面框
    handleUploadCover() {
      this.$refs.cover.click()
    },
    // 上传封面
    uploadCover(e) {
      let file = e.target.files[0]
      this.preview(file)
      let reader = new FileReader()
      reader.readAsBinaryString(file)
      reader.onload = e => {
        let md5 = require('md5')
        this.resourceForm.iconMd5value = md5(
          e.target.result.slice(0, 1024 * 1024 * 10)
        )
        let data = new FormData()
        data.append('file', file)
        data.append('iconMd5value', this.resourceForm.iconMd5value)
        this.$api
          .uploadResourceCover(data)
          .then(response => {
            this.$message.success('封面上传成功！')
          })
          .catch(_ => {
            this.$message.error('封面上传失败！')
          })
      }
    },
    // 封面预览
    preview(file) {
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = e => {
        this.previewCover = e.target.result
      }
    },
    // 打开上传文件框
    handleUploadResource() {
      this.$refs.resource.click()
    },
    // 文件上传后的预览及md5加密处理
    uploadResource(e) {
      let md5 = require('md5')
      let file = e.target.files[0]
      this.resourceForm.name = file.name
      this.resourceForm.guid = file.name
      this.previewResource = file
      let reader = new FileReader()
      reader.readAsBinaryString(file)
      reader.onload = e => {
        this.resourceForm.md5value = md5(
          e.target.result.slice(0, 1024 * 1024 * 10)
        )
      }
    },
    // 返回
    goback() {
      this.$router.back()
    },
    handleCheckChange() {
      let checkedNode = this.$refs.tree.getCheckedNodes()
      let ids = []
      checkedNode.forEach(node => {
        ids.push(node.id)
      })
      this.resourceForm.knowCateIds = ids.join(',')
    },
    // 确认上传
    handleUpload() {
      if (!this.previewResource) {
        this.$message.warning('请先选择需要上传的资源！')
        return
      }
      // 先判断选中的资源是否已经上传过
      const data = { md5value: this.resourceForm.md5value }
      this.$api.isResourceFileExist(data).then(response => {
        if (response.data.exist) {
          // 文件已经上传
          this.uploadExistFile()
        } else {
          // 文件还未上传
          this.splitFile()
        }
      })
    },
    // 文件已经上传，不需要再上传文件
    uploadExistFile() {
      let data = new FormData()
      data.append('knowCateIds', this.resourceForm.knowCateIds)
      data.append('title', this.resourceForm.title)
      data.append('resourceType', this.resourceForm.resourceType)
      data.append('brief', this.resourceForm.brief)
      data.append('md5value', this.resourceForm.md5value)
      data.append('name', this.resourceForm.name)
      data.append('iconMd5value', this.resourceForm.iconMd5value)
      this.$api
        .uploadResource(data)
        .then(_ => {
          this.$message.success('资源上传成功！')
          this.goback()
        })
        .catch(_ => {
          this.$message.error('资源上传失败！')
        })
    },
    // 文件切片
    splitFile() {
      // 初始化切片
      let file = this.previewResource // 需要分片上传的文件
      let splitSize = 5 * 1024 * 1024 // 每片文件的大小（5M）
      let size = file.size // 文件的总大小
      let start = 0 // 分片开始上传时的大小
      let end // 分片结束上传时的大小
      let index = 1 // 分片序号
      let totalPieces = Math.ceil(size / splitSize) // 总分片数
      // 初始化进度条
      this.uploadProgress = 0
      this.uploadDialogVisible = true
      this.upload(start, end, index, splitSize, size, file, totalPieces)
    },
    // 开始上传
    upload(start, end, index, splitSize, size, file, totalPieces) {
      if (start < size) {
        end = start + splitSize
        if (end > size) {
          end = size
        }
        let chunk = file.slice(start, end)
        let data = new FormData()
        Object.keys(this.resourceForm).forEach(key => {
          data.append(key, this.resourceForm[key])
        })
        data.append('file', chunk)
        data.append('chunks', totalPieces)
        data.append('chunk', index)
        this.$api
          .uploadResource(data)
          .then(response => {
            this.uploadProgress = Math.round(index / totalPieces * 100)
            start = end
            index++
            if (index > totalPieces) {
              this.$message.success('资源上传成功！')
              this.uploadDialogVisible = false
            }
            this.upload(start, end, index, splitSize, size, file, totalPieces)
          })
          .catch(_ => {
            this.$message.error('资源上传失败！')
            this.uploadDialogVisible = false
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~styles/mixin.scss';
.zygl-Upload {
  overflow: hidden;
  .content {
    height: 100%;
    display: flex;
    flex-direction: column;
    .el-button {
      line-height: 15px;
    }
    .title {
      height: 51px;
      padding: 0 20px;
      border-bottom: 1px solid #ccc;
      .upload-button {
        float: right;
        padding-top: 10px;
      }
      .crumbs {
        display: inline-block;
        padding-top: 20px;
      }
    }
    .main {
      flex: 1;
      overflow: auto;
      box-sizing: border-box;
      margin-bottom: 50px;
      .left {
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 30px;
        .cover {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          width: 178px;
          height: 178px;
          &:hover {
            border-color: #409eff;
          }
          .cover-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
          }
        }
      }
      .center {
        margin-top: 30px;
        height: 90%;
        .Knowledge-center {
          border: 1px solid #ccc;
          height: 100%;
          margin: 0 auto;
          width: 70%;
          display: flex;
          flex-direction: column;
          .center-tile {
            border-bottom: 1px solid #ccc;
            .association {
              display: inline-block;
              padding: 20px 10px;
            }
          }
          .center-tree {
            flex: 1;
            overflow: auto;
            @include scrollBar;
            padding: 10px 10px;
          }
        }
      }
      .right {
        margin-top: 30px;
        width: 36.5%;
        .el-form-item {
          margin-bottom: 14px;
        }
      }
    }
  }
}
</style>

